/**
 * @author huangyong
 */
public class MergeSort {
    public static int[] sort(int[] array) {
        return sort(array, 0, array.length-1);
    }

    private static int[] sort(int[] array, int left, int right) {
        if (left == right) {
            int temp = array[left];
            int[] newNum = {temp};
            return newNum;
        }

        int mid = left + (right - left) / 2;
        int[] leftArr = sort(array, left, mid);
        int[] rightArr = sort(array, mid + 1, right);
        int[] newNum = new int[leftArr.length + rightArr.length];

        int m = 0, i = 0, j = 0;
        while (i < leftArr.length && j < rightArr.length) {
            if (leftArr[i] < rightArr[j]) {
                newNum[m] = leftArr[i];
                i++;
            } else {
                newNum[m] = rightArr[j];
                j++;
            }
            m++;
        }
        while (i < leftArr.length) {
            newNum[m] = leftArr[i];
            m++;
            i++;
        }
        while (j < rightArr.length) {
            newNum[m] = rightArr[j];
            m++;
            j++;
        }
        return newNum;
    }
}
